strstr() — Locate Substring

Format

#include <string.h>
char *strstr(const char *string1, const char *string2);

Language Level

ANSI

Threadsafe

Yes

Description

The strstr() function finds the first occurrence of string2 in string1. The function ignores the null character (\0) that ends string2 in the matching process.

Return Value

The strstr() function returns a pointer to the beginning of the first occurrence of string2 in string1. If string2 does not appear in string1, the strstr() function returns NULL. If string2 points to a string with zero length, the strstr() function returns string1.

Example

This example locates the string "haystack" in the string "needle in a haystack".
#include <string.h>
#include <stdio.h>
 
int main(void)
{
   char *string1 = "needle in a haystack";
   char *string2 = "haystack";
   char *result;
 
   result = strstr(string1,string2);
   /* Result = a pointer to "haystack" */
   printf("%s\n", result);
}
 
/*****************  Output should be similar to: *****************
 
haystack
*/

Related Information